package com.sts.jdbc;

import com.sts.jdbc.model.ColumnInfo;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public interface JdbcOperation {

    List<String> getAllSchema(Connection connection);

    List<String> getAllTable(Connection connection, String schema);

    // 大写的字段名
    default Map<String, ColumnInfo> getTableAllColumn(Connection connection, String schema, String table) {
        LinkedHashMap<String, ColumnInfo> columnInfoMap = new LinkedHashMap<>();

        try (Connection con = connection) {
            DatabaseMetaData metaData = con.getMetaData();

            try (ResultSet resultSet = metaData.getColumns(null, schema, table, null)) {
                while (resultSet.next()) {
                    String columnName = resultSet.getString("COLUMN_NAME");
                    String typeName = resultSet.getString("TYPE_NAME");
                    int columnSize = resultSet.getInt("COLUMN_SIZE");
                    int precision = resultSet.getInt("DECIMAL_DIGITS");
                    boolean isNullable = resultSet.getBoolean("IS_NULLABLE");
                    String remarks = resultSet.getString("REMARKS");

                    columnInfoMap.put(columnName.toUpperCase(),
                            new ColumnInfo(columnName, typeName, columnSize, precision, isNullable, remarks));
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }

        return columnInfoMap;
    }

    Map<String, ColumnInfo> getTableAllPrimaryKeyColumn(Connection connection, String schema, String table);
}
